blog

Home / DeveloperSection / Blogs / BitConvertor Class in C#

BitConvertor Class in C#

Vijay Shukla3622 17-Jun-2013

In this blog I am trying to explain the concept of BitConvertor Class using C#.

BitConvertor Class

The BitConverter class helps manipulate value types in their fundamental form, as a series of bytes. A byte is defined as an 8-bit unsigned integer. The BitConverter class includes static methods to convert each of the primitive types to and from an array of bytes, as the following table illustrates.

Note: -

If you use BitConverter methods to round-trip data, make sure that the GetBytes overload and the ToType method specify the same type. As the following example illustrates.

Example: -
using System; 
public class Example
{
    public static void Main()
    {
        int value = -16;
        Byte[] bytes = BitConverter.GetBytes(value);
        // Convert bytes back to Int32.
        int intValue = BitConverter.ToInt32(bytes, 0);         Console.WriteLine("{0} = {1}: {2}",
                          value, intValue,
                          value.Equals(intValue) ? "Round-trips" : "Does not round-trip");         // Convert bytes to UInt32.
        uint uintValue = BitConverter.ToUInt32(bytes, 0);
        Console.WriteLine("{0} = {1}: {2}", value, uintValue,
                          value.Equals(uintValue) ? "Round-trips" : "Does not round-trip");         Console.ReadKey();
    }
}

Output: -

BitConvertor Class in C#

Updated 18-Sep-2014

Leave Comment

Comments

Liked By